package info.nightbrest.agt.shared.rpc.transport;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONException;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.inject.Inject;
import info.nightbrest.agt.client.AgtDispatcher;

public class SerializerImpl implements Serializer
{
	@Inject
	public SerializerImpl()
	{
	}

	@Override
	public String serialize(JavaScriptObject input, AgtDispatcher.RpcDataFormat format) throws Exception
	{
		switch (format)
		{
			case DATA_JSON_FORMAT:
				return toJSONString(input);

			// case DATA_XML_FORMAT:
			// case DATA_PLAIN_FORMAT:

			default:
				throw new Exception("Unsupported serialization format");
		}
	}

	@Override
	public JSONObject deserialize(String input, AgtDispatcher.RpcDataFormat format) throws Exception
	{
		switch (format)
		{
			case DATA_JSON_FORMAT:
				return fromJSONString(input);

			// case DATA_PLAIN_FORMAT:
			// case DATA_XML_FORMAT:

			default:
				throw new Exception("Unsupported serialization format");
		}
	}

	protected String toJSONString(JavaScriptObject jso) throws Exception
	{
		return new JSONObject(jso).toString();
	}

	protected JSONObject fromJSONString(String input) throws JSONException
	{
		return JSONParser.parseStrict(input).isObject();
	}
}
